# encoding: utf-8
from datetime import datetime, timedelta
from hashlib import md5

import jwt

import config

salt_bytes = config.SALT.encode('utf-8')


# 获取原始密码+salt的md5值
def create_md5(pwd):
    md5_obj = md5()
    md5_obj.update(pwd.encode('utf-8') + salt_bytes)
    return md5_obj.hexdigest()


def create_token(login_name):
    """
    创建token
    :param login_name: 用户的登录名
    :return: encoded_jwt
    """
    expiration_time = datetime.now() + timedelta(days=config.session_lifetime)
    token_dic = {
        'username': login_name,
        'expiration': expiration_time.timestamp()
    }
    encoded_jwt = jwt.encode(token_dic, config.SALT, algorithm='HS256')
    return encoded_jwt


def get_token_dict(auth_token):
    token_dict = jwt.decode(auth_token, config.SALT, algorithm='HS256')
    timestamp = token_dict.get('expiration', datetime.now().timestamp())
    token_dict.get('expiration', datetime.fromtimestamp(timestamp))
    return token_dict


def get_login_name_from_token(auth_token):
    token_dict = jwt.decode(auth_token, config.SALT, aalgorithm='HS256')
    expiration_time = token_dict.get('expiration', datetime.now().timestamp())
    if expiration_time > datetime.now().timestamp():
        return token_dict.get('username', None)
    return None


def validate_token(auth_token):
    token_dict = jwt.decode(auth_token, config.SALT, aalgorithm='HS256')
    expiration_time = token_dict.get('expiration', datetime.now().timestamp())
    if expiration_time > datetime.now().timestamp():
        return True
    return False